package com.mugui.spring.net.dblistener;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionStatus;

import com.mugui.sql.SqlServer;

@Configuration
public class SqlModeTransactionManager implements PlatformTransactionManager {

	private com.mugui.sql.SqlModel SqlModel = new com.mugui.sql.SqlModel();

	@Value("${mugui.SqlModel.status:false}")
	private boolean dataType;

	@Override
	public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
		if (dataType) {
			try {
				SqlModel.getSqlServer().setAutoCommit(false);
				if (definition.isReadOnly()) {
					SqlModel.getSqlServer().setLockOfSelect(true);
				}

			} catch (Exception e) {
				throw new RuntimeException(e);
			}
			return new DefaultTransactionStatus(definition, true, false, definition.isReadOnly(), false, null);
		}
		return null;
	}

	@Override
	public void commit(TransactionStatus status) throws TransactionException {
		if (dataType) {
			if (!SqlModel.getSqlServer().isAutoCommit()) {
				try {
					SqlModel.getSqlServer().commit();
				} catch (Exception e) {
					throw new RuntimeException(e);
				} finally {
					try {
						SqlModel.getSqlServer().setAutoCommit(true);
					} catch (Exception e) {
					}
				}
			}
			SqlServer.reback();
		}
	}

	@Override
	public void rollback(TransactionStatus status) throws TransactionException {
		System.out.println("rollback");
		if (dataType) {
			if (!SqlModel.getSqlServer().isAutoCommit()) {
				try {
					SqlModel.getSqlServer().rollback();
				} catch (Exception e) {
					throw new RuntimeException(e);
				} finally {
					try {
						SqlModel.getSqlServer().setAutoCommit(true);
					} catch (Exception e) {
					}
				}
			}
			SqlServer.reback();
		}
	}

}
